package org.example.wx.user.repository;

import org.example.wx.user.entity.ShippingAddress;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Repository
public interface ShippingAddressRepository extends JpaRepository<ShippingAddress, Long> {

    /**
     * 根据用户ID查询所有有效地址，按默认地址和更新时间排序
     */
    @Query("SELECT sa FROM ShippingAddress sa WHERE sa.userId = :userId AND sa.status = 1 ORDER BY sa.isDefault DESC, sa.updatedAt DESC")
    List<ShippingAddress> findByUserIdAndStatusOrderByIsDefaultDescUpdatedAtDesc(@Param("userId") Long userId);

    /**
     * 根据用户ID和地址ID查询地址
     */
    @Query("SELECT sa FROM ShippingAddress sa WHERE sa.id = :id AND sa.userId = :userId AND sa.status = 1")
    Optional<ShippingAddress> findByIdAndUserIdAndStatus(@Param("id") Long id, @Param("userId") Long userId);

    /**
     * 查询用户的默认地址
     */
    @Query("SELECT sa FROM ShippingAddress sa WHERE sa.userId = :userId AND sa.isDefault = true AND sa.status = 1")
    Optional<ShippingAddress> findDefaultByUserId(@Param("userId") Long userId);

    /**
     * 将用户的所有地址设为非默认
     */
    @Modifying
    @Transactional
    @Query("UPDATE ShippingAddress sa SET sa.isDefault = false WHERE sa.userId = :userId")
    int updateAllToNonDefault(@Param("userId") Long userId);

    /**
     * 逻辑删除地址
     */
    @Modifying
    @Transactional
    @Query("UPDATE ShippingAddress sa SET sa.status = 0 WHERE sa.id = :id AND sa.userId = :userId")
    int deleteByIdAndUserId(@Param("id") Long id, @Param("userId") Long userId);

    /**
     * 统计用户地址数量
     */
    @Query("SELECT COUNT(sa) FROM ShippingAddress sa WHERE sa.userId = :userId AND sa.status = 1")
    long countByUserIdAndStatus(@Param("userId") Long userId);
}
